<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产编号" prop="assetNumber">
        <el-input
          v-model="queryParams.assetNumber"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产名称" prop="assetName">
        <el-input
          v-model="queryParams.assetName"
          placeholder="请输入资产名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产类别" prop="assetCategory">
        <el-input
          v-model="queryParams.assetCategory"
          placeholder="请输入资产类别"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用部门" prop="useDepartment">
        <el-input
          v-model="queryParams.useDepartment"
          placeholder="请输入使用部门"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['assets:fixed:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['assets:fixed:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['assets:fixed:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['assets:fixed:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fixedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="资产编号" align="center" prop="assetNumber" />
      <el-table-column label="资产名称" align="center" prop="assetName" />
      <el-table-column label="规格型号" align="center" prop="specificationModel" />
      <el-table-column label="资产类别" align="center" prop="assetCategory" />
      <el-table-column label="使用部门" align="center" prop="useDepartment" />
      <el-table-column label="使用人" align="center" prop="user" />
      <el-table-column label="开始使用日期" align="center" prop="startUseDate" width="180"/>
      <el-table-column label="资产原值" align="center" prop="originalValue" />
      <el-table-column label="折旧方式" align="center" prop="depreciationMethod" />
      <el-table-column label="预计使用年限" align="center" prop="estimatedLife" />
      <el-table-column label="已使用/总期数" align="center" prop="usedTotalPeriods" />
      <el-table-column label="每月折旧额" align="center" prop="monthlyDepreciation" />
      <el-table-column label="残值率（%）" align="center" prop="residualRate" />
      <el-table-column label="预计残值" align="center" prop="estimatedResidual" />
      <el-table-column label="期初净值" align="center" prop="initialNetValue" />
      <el-table-column label="期末净值" align="center" prop="endingNetValue" />
      <el-table-column label="录入期间" align="center" prop="entryPeriod" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['assets:fixed:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['assets:fixed:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改固定资产对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="fixedRef" :model="form" :rules="rules" label-width="80px">
        <span>基本信息</span>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产编号">
              <el-input v-model="form.assetNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产名称">
              <el-input v-model="form.assetName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号">
              <el-input v-model="form.specification"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产类别">
              <el-select v-model="form.assetCategory" placeholder="请选择资产类别">
                <el-option
                    v-for="item in assetCategories"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用部门">
              <el-select v-model="form.useDepartment" placeholder="请选择使用部门">
                <el-option
                    v-for="item in useDepartments"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用人">
              <el-input v-model="form.user"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购入日期" prop="purchaseDate">
              <el-date-picker clearable
                              v-model="form.purchaseDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择购入日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="录入期间" prop="entryPeriod">
              <el-date-picker clearable
                              v-model="form.entryPeriod"
                              type="date"
                              value-format="YYYY-MM"
                              placeholder="请选择录入期间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始使用日期" prop="startUseDate">
              <el-date-picker clearable
                              v-model="form.startUseDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择购入日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存放位置">
              <el-input v-model="form.location"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商">
              <el-select v-model="form.supplier" placeholder="请选择供应商">
                <el-option
                    v-for="item in suppliers"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增加类型">
              <el-select v-model="form.addType" placeholder="请选择增加类型">
                <el-option
                    v-for="item in addTypes"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="复制张数">
              <el-input v-model="form.copyCount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否录入当期折旧">
              <el-radio-group v-model="form.depreciateNow">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <span>折旧方式</span>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="折旧方式">
              <el-select v-model="form.depreciationMethod" placeholder="请选择折旧方式">
                <el-option label="平均年限法" value="平均年限法"></el-option>
                <el-option label="不计提折旧" value="不计提折旧"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="减值准备科目">
              <el-input v-model="form.impairmentAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="固定资产科目">
              <el-input v-model="form.fixedAssetAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="累计折旧科目">
              <el-input v-model="form.accumDepreciationAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折旧费用科目">
              <el-input v-model="form.depreciationExpenseAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税金科目">
              <el-input v-model="form.taxAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产清理科目">
              <el-input v-model="form.assetDisposalAccount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产购入对方科目">
              <el-input v-model="form.purchaseAccount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <span>资产数据</span>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产原值">
              <el-input v-model="form.originalValue" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税额">
              <el-input v-model="form.taxAmount" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="残值率（%）">
              <el-input v-model="form.residualRate" placeholder="请输入"><template #append>%</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计残值">
              <el-input
                  v-model="form.estimatedResidual"
                  :disabled="true"
                  :value="estimatedResidual" placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="减值准备">
              <el-input v-model="form.impairment" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计使用年限">
              <el-input v-model="form.estimatedLife" placeholder="请输入"><template #append>个月</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已折旧期间">
              <el-input v-model="form.depreciatedPeriods" placeholder="请输入"><template #append>个月</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余使用期间">
              <el-input
                  v-model="form.remainingPeriods"
                  :disabled="true"
                  :value="remainingPeriods" placeholder="请输入"
              ><template #append>个月</template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期初累计折旧">
              <el-input
                  v-model="form.accumDepreciation"
                  :disabled="true"
                  :value="accumDepreciation" placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每月折旧额">
              <el-input
                  v-model="form.monthlyDepreciation"
                  :disabled="true"
                  :value="monthlyDepreciation" placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期初净值">
              <el-input
                  v-model="form.initialNetValue"
                  :disabled="true"
                  :value="initialNetValue" placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Fixed">
import { listFixed, getFixed, delFixed, addFixed, updateFixed, findType } from "@/api/assets/fixed";
import axios from "axios";
import { onMounted,reactive,ref } from "vue";

const { proxy } = getCurrentInstance();

const fixedList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const assetCategories = ref([]);

const useDepartments = ref([]);

const suppliers = ref([]);

const addTypes = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    assetNumber: null,
    assetName: null,
    assetCategory: null,
    useDepartment: null,
  },
  rules: {
    assetNumber: [
      { required: true, message: "资产编号不能为空", trigger: "blur" }
    ],
    assetName: [
      { required: true, message: "资产名称不能为空", trigger: "blur" }
    ],
  }
});
// 计算资产数据
const estimatedResidual = computed(() => {
  const residualRate = parseFloat(form.value.residualRate) || 0;
  const originalValue = parseFloat(form.value.originalValue) || 0;
  return ((residualRate * originalValue) / 100).toFixed(2);
});

const remainingPeriods = computed(() => {
  const estimatedLife = parseFloat(form.value.estimatedLife) || 0;
  const depreciatedPeriods = parseFloat(form.value.depreciatedPeriods) || 0;
  return (estimatedLife - depreciatedPeriods).toFixed(2);
});

const initialNetValue = computed(() => {
  const originalValue = parseFloat(form.value.originalValue) || 0;
  const impairment = parseFloat(form.value.impairment) || 0;
  return (originalValue - impairment).toFixed(2);
});

const monthlyDepreciation = computed(() => {
  const originalValue = parseFloat(form.value.originalValue) || 0;
  const estimatedResidual = parseFloat(form.value.estimatedResidual) || 0;
  const estimatedLife = parseFloat(form.value.estimatedLife) || 0;
  if (estimatedLife === 0) return 0; // 防止除以0
  return ((originalValue - estimatedResidual) / estimatedLife).toFixed(2);
});

const accumDepreciation = computed(() => {
  const monthlyDepreciation = parseFloat(form.value.monthlyDepreciation) || 0;
  const depreciatedPeriods = parseFloat(form.value.depreciatedPeriods) || 0;
  return (monthlyDepreciation * depreciatedPeriods).toFixed(2);
});

const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  findType().then(response => {
    console.log('完整响应对象:', response); // 打印完整响应
    console.log('响应数据层级:', response.data);
    console.log('实际数据内容:', response.data?.data); // 检查是否存在嵌套
    if (response) {
      if(response['asset_category']){
        console.log('Asset Categories:', response['asset_category']); // 检查资产类别数据
        assetCategories.length = 0; // 清空现有数据
        assetCategories.value = response['asset_category'] || [];
      }

      if(response['use_department']){
        console.log('Use Departments:', response['use_department']); // 检查使用部门数据
        useDepartments.length = 0;
        useDepartments.value = response['use_department'] || [];
      }

      if(response['supplier']){
        console.log('Suppliers:', response['supplier']); // 检查供应商数据
        suppliers.length = 0;
        suppliers.value = response['supplier'] || [];
      }

      if(response['add_type']){
        console.log('Add Types:', response['add_type']); // 检查增加类型数据
        addTypes.length = 0;
        addTypes.value = response['add_type'] || [];
      }
    }
    console.log('Final Asset Categories:', assetCategories);
    console.log('Final Use Departments:', useDepartments);
    console.log('Final Suppliers:', suppliers);
    console.log('Final Add Types:', addTypes);
  }).catch(error => {
    console.error('Error fetching dictionary data:', error);
  });
});

/** 查询固定资产列表 */
function getList() {
  loading.value = true;
  listFixed(queryParams.value).then(response => {
    fixedList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    assetNumber: null,
    assetName: null,
    specification: null,
    assetCategory: null,
    purchaseDate: null,
    entryPeriod: null,
    startUseDate: null,
    location: null,
    useDepartment: null,
    user: null,
    supplier: null,
    addType: null,
    copyCount: null,
    depreciateNow: true,
    remark: null,
    depreciationMethod: null,
    impairmentAccount: '1603 固定资产减值准备',
    fixedAssetAccount: '1601 固定资产',
    accumDepreciationAccount: '1602 累计折旧',
    depreciationExpenseAccount: '1603 固定资产减值准备',
    taxAccount: '22210101 应交税费_应交增值税_进项税额',
    assetDisposalAccount: '1606 固定资产清理',
    purchaseAccount: '1002 银行存款',
    originalValue: '',
    taxAmount: '',
    residualRate: '',
    estimatedResidual: '',
    impairment: '',
    estimatedLife: '',
    depreciatedPeriods: '',
    remainingPeriods: '',
    accumDepreciation: '',
    monthlyDepreciation: '',
    initialNetValue: ''
  };
  proxy.resetForm("fixedRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 生成以大写字母开头，总长度为5的资产编号
  const snowflakeId = generateSnowflakeId();
  const randomLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26)); // 生成A-Z的随机字母
  form.value.assetNumber = (randomLetter + snowflakeId.toString().slice(-4)).toUpperCase();
  open.value = true;
  title.value = "添加固定资产";
}

function generateSnowflakeId() {
  const epoch = 1609459200000; // 2021-01-01
  let sequence = 0;
  let lastTimestamp = -1;

  function nextId() {
    let timestamp = Date.now() - epoch;
    if (timestamp === lastTimestamp) {
      sequence = (sequence + 1) & 0xFFF;
      if (sequence === 0) {
        timestamp++;
        while (timestamp <= lastTimestamp) {
          timestamp = Date.now() - epoch;
        }
      }
    } else {
      sequence = 0;
    }
    lastTimestamp = timestamp;
    return ((timestamp << 12) | sequence).toString();
  }
  return nextId();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getFixed(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改固定资产";
  });
}

/** 提交按钮 */
function submitForm() {
  // 手动触发一次计算逻辑，确保所有计算结果是最新的
  form.value.estimatedResidual = estimatedResidual.value;
  form.value.remainingPeriods = parseFloat(remainingPeriods.value).toFixed(0);
  form.value.initialNetValue = initialNetValue.value;
  form.value.monthlyDepreciation = monthlyDepreciation.value;
  form.value.accumDepreciation = accumDepreciation.value;

  proxy.$refs["fixedRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFixed(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFixed(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除固定资产编号为"' + _ids + '"的数据项？').then(function() {
    return delFixed(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('assets/fixed/export', {
    ...queryParams.value
  }, `fixed_${new Date().getTime()}.xlsx`)
}

getList();
</script>
